package com.zhdl.network.common_client;

import cn.hutool.core.util.HexUtil;
import com.project.command.instruction.strategy.abs.AbsAfterControlCommand;
import com.project.command.instruction.strategy.process.data.AfterStrategyParam;
import com.project.common.util.ByteHelper;
import com.zhdl.common.ytools.eventbus.center.EventBusCenter;
import com.zhdl.network.common_client.dto.ModbusSerialDto;
import com.zhdl.network.common_client.resp.CommonClientEvent;
import com.zhdl.network.other_protocol.modbusrtu.dto.ModbusDto;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service(CommonSerialClientAfter.MODBUS_RTU_AFTER_SERVICE)
public class CommonSerialClientAfter extends AbsAfterControlCommand<ModbusSerialDto, ByteBuf> {

    public static final String MODBUS_RTU_AFTER_SERVICE = "CommonSerialClientAfter";

    /**
     * 后置处理结果判断
     *
     * @param resp
     * @return
     */
    @Override
    public boolean afterResultJudge(AfterStrategyParam resp) {
        /*
            判断当前线程以及执行的哪一个after
         */
        log.debug("CommonSerialClientAfter---->{}", Thread.currentThread().getName());

        //此处接收串口或网口客户端回应代码,并处理
        List<ModbusSerialDto> list = resp.getNewData();
        ModbusSerialDto modbusSerialDto = list.get(0);

        CommonClientEvent protocolEvent = new CommonClientEvent();
        protocolEvent.setPort(resp.getPortKey());
        protocolEvent.setProtocol(resp.getProtocols());
        protocolEvent.setSendCmd(resp.getInstruction());
        protocolEvent.setReceiveData(modbusSerialDto.getFullBuff());
        EventBusCenter.getEventBus().post(protocolEvent);

        log.info("CommonSerialService---->{}-发送指令>>>>>>>>{}-收到指令>>>>>>>>{}",
                resp.getPortKey(), resp.getInstruction(), ByteHelper.byteToString(modbusSerialDto.getFullBuff()));
        return true;
    }

    /**
     * 判断 读取 3200 状态字数据
     */
    public String getMotorStatus(ModbusDto modbusDto) {
        byte[] unitBuff = modbusDto.getUnitBuff();
        return HexUtil.encodeHexStr(unitBuff);
    }

}
